<template>
    <div>
        <!-- 对数据操作  -->
        <div class="tool-rows">
            <el-input v-model="name" placeholder="请输入博文标题" class="table-input" suffix-icon="el-icon-edit"></el-input>
            <el-input v-model="uploader" placeholder="请输入博文作者" class="table-input" suffix-icon="el-icon-user"></el-input>
            <el-button type="success" icon="el-icon-search" @click="load">搜索</el-button>
            <el-button type="warning" icon="el-icon-refresh-right" @click="reset">重置</el-button>
        </div>
        <div class="tool-rows">
            <el-button type="success" icon="el-icon-upload2" @click="handleUpload">博文发布</el-button>
            <el-popconfirm
                    confirm-button-text='确定'
                    cancel-button-text='取消'
                    icon="el-icon-info"
                    icon-color="red"
                    @confirm="handleBatchDelete"
                    title="确定删除选中博文吗?">
                <el-button type="danger"
                           icon="el-icon-delete"
                           slot="reference"
                           v-show="user.role === 'USER_ADMIN'"
                           style="margin: 0 10px">批量删除</el-button>
            </el-popconfirm>
        </div>

        <!-- 表单区域  -->
        <el-table :data="tableData" header-cell-class-name="table-header" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="50">
            </el-table-column>
            <el-table-column prop="name" label="标题" width="365">
            </el-table-column>
            <el-table-column prop="uploader" label="发布人">
            </el-table-column>
            <el-table-column prop="time" label="发布时间">
            </el-table-column>
            <el-table-column prop="operation" label="操作" width="360" align="center">
                <template slot-scope="scope">
                    <el-button type="success" icon="el-icon-view" @click="handleDetail(scope.row.id)">查看详情</el-button>
                    <el-button type="info"
                               icon="el-icon-edit"
                               v-show="user.role === 'USER_ADMIN' || scope.row.uploader === user.userName"
                               @click="editArticle(scope.row)">修改</el-button>
                    <el-popconfirm
                            confirm-button-text='确认'
                            cancel-button-text='取消'
                            icon="el-icon-info"
                            icon-color="red"
                            v-show="user.role === 'USER_ADMIN' || scope.row.uploader === user.userName"
                            @confirm="handleDelete(scope.row.id)"
                            title="确定删除该博文吗?">
                        <el-button type="danger" icon="el-icon-delete" slot="reference" style="margin-left: 6px">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页条  -->
        <div class="tool-rows">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNumber"
                    :page-sizes="[5, 10, 15]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <!-- 在此输入文件描述  -->
        <el-dialog title="博文发布" :visible.sync="dialogFormVisible" width="60%" custom-class="edit-dialog">
            <el-form :model="articleForm">
                <el-form-item label="博文标题" label-width="80px">
                    <el-input v-model="articleForm.name" placeholder="请输入博文标题"></el-input>
                </el-form-item>
                <el-form-item label="博文内容" label-width="80px">
                    <mavon-editor ref="md"
                                  v-model="articleForm.content"
                                  :ishljs="true"
                                  @imgAdd="imgAdd">
                    </mavon-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveArticle">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import axios from "axios";

    export default {
        name: "Article",
        data () {
            return {
                // 用户信息
                user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null,
                // 博文发布
                articleForm: {},
                dialogFormVisible: false,
                // 分页控件
                pageNumber: 1,
                pageSize: 5,
                total: 0,
                name: '',
                uploader: '',
                // 表格数据
                tableData: [],
                multipleSelection: []
            }
        },
        created () {
            this.load()
        },
        methods: {
            // 分页加载
            load () {
                this.request.get('/article/page', {
                    params: {
                        pageNumber: this.pageNumber,
                        pageSize: this.pageSize,
                        name: this.name,
                        uploader: this.uploader
                    }
                }).then(res => {
                    this.tableData = res.data.records
                    this.total = res.data.total
                })
            },
            handleSizeChange(pageSize) {
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNumber) {
                this.pageNumber = pageNumber
                this.load()
            },
            reset () {
                this.name = ''
                this.load()
            },
            // 发布文章
            handleUpload () {
                this.articleForm = {}
                this.dialogFormVisible = true
                this.load()
            },
            saveArticle () {
                this.request.post('/article', this.articleForm).then(res => {
                    if (res.code === '200') {
                        this.$message.success('发布成功!')
                        this.dialogFormVisible = false
                        this.load()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            editArticle (row) {
                this.articleForm = row
                this.dialogFormVisible = true
                this.load()
            },
            // 删除
            handleDelete (id) {
                this.request.delete('/article/' + id).then(res => {
                    if (res.code === '200') {
                        this.$message.success('删除成功!')
                        this.load()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            handleBatchDelete () {
                let ids = this.multipleSelection.map(v => v.id)
                this.request.post('/article/del/batch', ids).then(res => {
                    if (res.code === '200') {
                        this.$message.success('批量删除成功!')
                        this.load()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            // 查看文章详情
            handleDetail (id) {
                this.$router.push({ path: '/articledetail',
                                    query: {id: id}
                                   })
            },
            // mavon-editor的上传图片方法
            imgAdd(pos, $file) {
                let $vm = this.$refs.md
                // 第一步.将图片上传到服务器.
                const formData = new FormData();
                formData.append('file', $file);
                axios({
                    url: `http://localhost:18080/blog-file/upload`,
                    method: 'post',
                    data: formData,
                    headers: {'Content-Type': 'multipart/form-data',
                              'token': this.user.token},
                }).then((res) => {
                    // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
                    // 因为结果集的缘故似乎要解析两次...
                    $vm.$img2Url(pos, res.data.data);
                })
            },
        }
    }
</script>

<style scoped>
    div.tool-rows {
        margin: 16px 0;
    }
    .table-input{
        display: inline-block;
        margin-right: 15px;
        width: 200px;
    }
    /deep/ div.el-dialog__body {
        padding-bottom: 10px !important;
    }
    /deep/ .table-header {
        background-color: #E4E4E4 !important;
    }
    /deep/ .edit-dialog {
        border-radius: 12px !important;
    }
</style>